import React, { createContext, useContext, useState, useEffect } from 'react';
import PropTypes from 'prop-types';

const UserContext = createContext();

export const UserProvider = ({ children }) => {
  const [userRoles, setUserRoles] = useState(JSON.parse(localStorage.getItem('userRoles')) || ['guest']);

  useEffect(() => {
    const storedUserInfo = localStorage.getItem('userInfo');
    if (storedUserInfo) {
      const { roles } = JSON.parse(storedUserInfo);
      setUserRoles(roles);
    }
  }, []);

  const setRoles = (roles) => {
    setUserRoles(roles);
    localStorage.setItem('userRoles', JSON.stringify(roles));
  };

  return (
    <UserContext.Provider value={{ userRoles, setRoles }}>
      {children}
    </UserContext.Provider>
  );
};

UserProvider.propTypes = {
  children: PropTypes.node.isRequired,
};

export const useUserContext = () => useContext(UserContext);
